package com.cgtong.android.fragment;


import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.cgtong.android.R;
import com.cgtong.android.activity.ProblemDetailActivity;
import com.cgtong.android.adapter.ReportsAdapter;
import com.cgtong.android.base.BaseLazyFragment;
import com.cgtong.android.bean.FilterBean;
import com.cgtong.android.bean.ProblemBean;
import com.cgtong.android.callback.ErrorCallback;
import com.cgtong.android.http.ConstantManager;
import com.cgtong.android.mvp.contract.MyReportContract;
import com.cgtong.android.mvp.presenter.MyReportPresenter;
import com.cgtong.android.util.PostUtil;
import com.cgtong.android.widget.BaseDialog;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.ApiResult;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 我的上报分页
 */
public class MyReportsFragment extends BaseLazyFragment implements MyReportContract.View {

    private static final String KEY_TAB_STATUS = "tab_status";
    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R.id.swipe_layout)
    SwipeRefreshLayout mSwipeLayout;

    @BindView(R.id.search_txt)
    TextView mSearchTxt;
    @BindView(R.id.search_edt)
    EditText mSearchEdt;
    @BindView(R.id.clear_img)
    ImageView mClearImg;
    @BindView(R.id.search_fl)
    FrameLayout mSearchFl;

    public final static int ALL = 0;//0全部
    public final static int REPORTED = 1;//1已上报
    public final static int TOVOID = 6;//6已作废
    public final static int ACCEPTANCE = 2;//2已受理
    public final static int CLOSE = 4;//4已结案
    public final static int EVALUATE = 5;//5已评价
    public final static int UNREPORTED = 7;//7未上报


    private int mTabStatus;//0全部，1已上报，2已受理，3处理中，4已结案

    private int mStatus = 0; //状态位，0全部，1已上报，2已受理，3处理中，4已结案 5已评价 6已作废
    private int mIsExpired = 0;//是否超期，0全部，1，已超期，2，未超期
    private List<ProblemBean> mList;
    private BaseQuickAdapter<ProblemBean, BaseViewHolder> mAdapter;
    private int defaultDelete = -1;

    private MyReportContract.Presenter mPresenter;
    private String mSearchKey = "";

    //时间范围
    private String mBeginTime = "";
    private String mEndTime = "";


    public static MyReportsFragment newInstance(int tabStatus) {
        Bundle args = new Bundle();
        args.putInt(KEY_TAB_STATUS, tabStatus);
        MyReportsFragment fragment = new MyReportsFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public int getLayoutId() {
        return R.layout.fragment_my_reports;
    }

    @Override
    public void initData() {
        mPresenter = new MyReportPresenter(this);
        mList = new ArrayList<>();
        initRecyclerView();
        mTabStatus = getArguments().getInt(KEY_TAB_STATUS);
        mStatus = mTabStatus;
        LogUtils.d("tabstatus ============= " + mTabStatus);
//        if (mTabStatus == 0) {
//            mStatus = 0;
//            mIsExpired = 0;
//        } else if (mTabStatus == 1) {
//            mStatus = 1;
//            mIsExpired = 0;
//        } else if (mTabStatus == 2) {
//            mStatus = 2;
//            mIsExpired = 0;
//        } else if (mTabStatus == 4) {
//            mStatus = 4;
//            mIsExpired = 0;
//        } else if (mTabStatus == 5) {
//            mStatus = 5;
//            mIsExpired = 0;
//        } else if (mTabStatus == 6) {
//            mStatus = 6;
//            mIsExpired = 0;
//        }
        mIsExpired = 0;
        //回车键搜索监听
        mSearchEdt.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        mSearchEdt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    mSearchKey = mSearchEdt.getText().toString();
                    mPresenter.httpReportsData("", mStatus, mIsExpired, mSearchKey, mBeginTime, mEndTime, true);
                    KeyboardUtils.hideSoftInput(mSearchEdt);
//                    mSearchEdt.setText("");
                    return false;
                }
                return false;
            }
        });
        //显示或隐藏清空按钮
        mSearchEdt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() == 0) {
                    mClearImg.setVisibility(View.GONE);
                    mSearchKey = "";
//                    loadDataByNet();
                } else {
                    mClearImg.setVisibility(View.VISIBLE);
                }
            }
        });
    }


    /**
     * 初始化列表
     */

    private void initRecyclerView() {
        mSwipeLayout.setColorSchemeResources(R.color.color_scheme);
        mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mPresenter.httpReportsData("", mStatus, mIsExpired, mSearchKey, mBeginTime, mEndTime, true);
            }
        });
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter = new ReportsAdapter(mList);
        mRecyclerView.setAdapter(mAdapter);
//        mRecyclerView.addItemDecoration(new RecycleViewDivider(getActivity(), LinearLayoutManager.HORIZONTAL, R.drawable.shape_horizontal_divider));
        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                String maxTime = mAdapter.getItem(mAdapter.getItemCount() - 2).getCreateTime();
                mPresenter.httpReportsData(maxTime, mStatus, mIsExpired, mSearchKey, mBeginTime, mEndTime, false);

            }
        }, mRecyclerView);
        mAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ProblemBean problemBean = mAdapter.getItem(position);
                LogUtils.d("problemBean= " + problemBean.toString());
                boolean canDelete = false;
                boolean canEvaluate = false;
//                if (mTabStatus == 0 || mTabStatus == 1) {
                if (problemBean.getStatus() == CLOSE
                        || problemBean.getStatus() == EVALUATE
                        || problemBean.getStatus() == TOVOID
                        || problemBean.getStatus() == UNREPORTED) {
                    canDelete = true;
                }
                if (problemBean.getStatus() == CLOSE || problemBean.getStatus() == EVALUATE) {
                    canEvaluate = true;
                }
//                }
                ProblemDetailActivity.startForResult(getActivity(), problemBean.getId(), canDelete, canEvaluate, position);
//                ProblemDetailActivity.start(getActivity(), mAdapter.getItem(position).getId(), canDelete, canEvaluate);
            }
        });
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                ProblemBean problemBean = mAdapter.getItem(position);
                defaultDelete = position;
                LogUtils.d("delete problemBean= " + problemBean.toString());
//                mPresenter.deleteReport(problemBean.getId());
                showDeleteDialog(problemBean.getId());
            }
        });
    }


    @Override
    protected void loadDataByNet() {
        LogUtils.d("beginTime = " + mBeginTime + " endTime = " + mEndTime);
        mPresenter.httpReportsData("", mStatus, mIsExpired, mSearchKey, mBeginTime, mEndTime, true);
    }

    @Override
    protected void onDataReloadByNet(View v) {
        mSearchKey = "";
        mPresenter.httpReportsData("", mStatus, mIsExpired, mSearchKey, mBeginTime, mEndTime, true);

    }

    @Override
    public void setRefreshing(boolean isRefresh) {
        if (mSwipeLayout != null) {
            mSwipeLayout.setRefreshing(isRefresh);
        }
    }

    @Override
    public void setEnableLoadMore(boolean enableLoadMore) {
        mAdapter.setEnableLoadMore(enableLoadMore);
    }

    @Override
    public void onLoadMoreEnd(boolean isLoadMoreEnd) {
        mAdapter.loadMoreEnd(isLoadMoreEnd);
    }

    @Override
    public void onDeleteReportFail(ApiException e) {
        PostUtil.postCallbackDelayed(loadService, ErrorCallback.class);
    }

    @Override
    public void onError(ApiException e) {
        PostUtil.postSuccessDelayed(loadService);
        mAdapter.setNewData(null);
        mAdapter.setEmptyView(R.layout.layout_error);
    }


    @Override
    public void onNullData() {
        PostUtil.postSuccessDelayed(loadService);
        mAdapter.setNewData(null);
        mAdapter.setEmptyView(R.layout.layout_empty);
    }

    @Override
    public void onHttpReportsDataSuccess(List<ProblemBean> datas, boolean isRefresh) {
        PostUtil.postSuccessDelayed(loadService);
        if (isRefresh) {
            mAdapter.setNewData(datas);
//            mAdapter.disableLoadMoreIfNotFullPage(mRecyclerView);
        } else {
            mAdapter.addData(datas);
        }
        mAdapter.loadMoreComplete();
    }

    @OnClick({R.id.clear_img, R.id.search_bar_fl})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.clear_img:
                mSearchKey = "";
                mSearchEdt.setText("");
                KeyboardUtils.hideSoftInput(mSearchEdt);
                loadDataByNet();

                break;
            case R.id.search_bar_fl:
                mSearchFl.setVisibility(View.VISIBLE);
                mSearchTxt.setVisibility(View.GONE);
                KeyboardUtils.showSoftInput(mSearchEdt);
                break;
        }
    }

    private void showDeleteDialog(final long mProblemId) {
        BaseDialog.create(getFragmentManager())
                .setLayoutRes(R.layout.layout_delete_dialog)
                .setViewListener(new BaseDialog.ViewListener() {

                    @Override
                    public void bindView(View view, final Dialog dialog) {
                        TextView okTxt = (TextView) view.findViewById(R.id.delete_txt);
                        okTxt.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mPresenter.deleteReport(mProblemId);
                                dialog.cancel();
                            }
                        });
                        TextView noTxt = (TextView) view.findViewById(R.id.cancel_txt);
                        noTxt.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.cancel();
                            }
                        });
                    }
                }).setDimAmount(0.3f)
                .setCanCancelable(false).
                setGravity(Gravity.BOTTOM)
                .show();
    }

    @Override
    public void onDeleteReportSuccess(ApiResult result) {
        if (result.getCode() == 0) {
            if (defaultDelete != -1) {
                long id = mAdapter.getData().get(defaultDelete).getId();
                mAdapter.remove(defaultDelete);
                if (mAdapter.getItemCount() == 0) {
                    mAdapter.setNewData(null);
                    mAdapter.setEmptyView(R.layout.layout_empty);
                }
                EventBus.getDefault().post(new ProblemBean(id), ConstantManager.DELETE_REPORT_TAG);
                return;
            }
        }
        ToastUtils.showShort(result.getMsg());
    }

    @Subscriber(tag = ConstantManager.DELETE_REPORT_TAG)
    private void deleteReport(ProblemBean problemBean) {
        LogUtils.d("删除id为：" + problemBean.getId());
        //更新 全部，待处理，已完结列表页
        if (mTabStatus == 0 || mTabStatus == 1 || mTabStatus == 4) {
            List<ProblemBean> list = mAdapter.getData();
            for (int i = 0; i < list.size(); i++) {
                ProblemBean bean = list.get(i);
                if (bean.getId() == problemBean.getId()) {
                    mAdapter.remove(i);
                }
            }
            if (mAdapter.getItemCount() == 0) {
                mAdapter.setNewData(null);
                mAdapter.setEmptyView(R.layout.layout_empty);
            }
        }
    }

    /**
     * 接收传输的时间范围
     *
     * @param filter
     */
    @Subscriber(tag = ConstantManager.FILTER_TIME_AREA_TAG)
    private void doFilter(FilterBean filter) {
        mBeginTime = filter.getBeginTime();
        mEndTime = filter.getEndTime();
        if (mPresenter == null) {
            return;
        }
        LogUtils.d("starttime: " + mBeginTime + " endtime: " + mEndTime);
        loadDataByNet();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 注册对象
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        // 注销
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

}
